from langchain_mcp_adapters.client import MultiServerMCPClient
import settings
from .statics import static_tools
from models.mcp_handlers import get_mcp_servers,get_mcp_version
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger
from blinker import signal
from typing import Callable

class ZLToolManager:
    def __init__(self):
        self.mcp_version: str | None = None
        self.scheduler = AsyncIOScheduler()
        self.mcp_changed_signal = signal("mcp-changed-signal")

    async def get_tools(self):
        servers = await get_mcp_servers()
        mcps = {}
        for server in servers:
            mcp = {"transport": server.transport}
            if server.transport == "sse" or server.transport == "streamable_http":
                mcp['url'] = server.url
                mcp['headers'] = server.headers
            else:
                mcp['args'] = server.args
                mcp['command'] = server.command
                mcp['env'] = server.env
            mcps[server.name] = mcp

        mcp_clint = MultiServerMCPClient(mcps)
        mcp_tools = await mcp_clint.get_tools()
        return mcp_tools + static_tools

    def connect_signal(self, callback: Callable):
        self.mcp_changed_signal.connect(callback, sender=self)

    async def _detect_mcp(self):
        print("执行了_detect_mcp方法")
        version_model = await get_mcp_version()
        if self.mcp_version != version_model.version:
            self.mcp_version = version_model.version
            await self.mcp_changed_signal.send_async(self)
            print("由于数据库中的版本跟内存中不一样，所以走到这里了")

    def star_scheduler(self):
        self.scheduler.add_job(
            func=self._detect_mcp,
            trigger=IntervalTrigger(seconds=settings.MCP_DETECT_INTERVAL)
        )
        self.scheduler.start()

